package com.longway.core.toolbox.wdp.msg;

import java.util.Arrays;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.longway.core.toolbox.utils.XmlHelper;
import com.longway.core.toolbox.wdp.WdpConfig;
import com.longway.core.toolbox.wdp.WdpConfigKit;

/**
 * 第三方授权消息拦截器
 */
public class WdpAuthEventInterceptor implements Interceptor {
    private static final Log log = Log.getLog(WdpAuthEventInterceptor.class);
    

    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        if (!(controller instanceof WdpAuthEventController)) {
            throw new RuntimeException("控制器需要继承 WdpAuthEventController");
        }
        // 获取配置
        WdpConfig wdpConfig = WdpConfigKit.getWdpConfig();
        String token = wdpConfig.getToken();
        // 对开发测试更加友好
        if (WdpConfigKit.isDevMode()) {
            inv.invoke();
        } else {
            // 签名检测
            if (checkSignature(controller, token)) {
                inv.invoke();
            } else {
                controller.renderText("签名验证失败，请确定是微信服务器在发送消息过来");
            }
        }
    }

    /**
     * 检测签名
     */
    private boolean checkSignature(Controller c, String token) {
    	String msgSignature = c.getPara("msg_signature");
		String nonce = c.getPara("nonce");
		String timestamp = c.getPara("timestamp");
		String postdata = c.getRawData();
		XmlHelper xmlHelper = XmlHelper.of(postdata);
		String encryptContent = xmlHelper.getString("//Encrypt");
        if (StrKit.isBlank(msgSignature) || StrKit.isBlank(timestamp) || StrKit.isBlank(nonce)) {
            c.renderText("check signature failure");
            return false;
        }

        if (checkSignature(msgSignature, token, timestamp, nonce,encryptContent)) {
            return true;
        } else {
            log.error("check signature failure: " +
                " signature = " + c.getPara("signature") +
                " timestamp = " + c.getPara("timestamp") +
                " nonce = " + c.getPara("nonce"));

            return false;
        }
    }

    private boolean checkSignature(String msgSignature, String token, String timestamp, String nonce ,String encryptContent) {
        String array[] = {token, timestamp, nonce ,encryptContent};
        Arrays.sort(array);
        String tempStr = array[0] + array[1] + array[2] + array[3];;
        tempStr = HashKit.sha1(tempStr);
        return tempStr.equalsIgnoreCase(msgSignature);
    }

}
